package cn.easytogo.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import cn.easytogo.bean.Role;
import cn.easytogo.bean.RoleAndResource;
import cn.easytogo.service.IRoleDAO;

public class RoleDAOImpl extends BaseService implements IRoleDAO {

	public List selectRolesByMap(Map map) throws SQLException {
		return this.getBaseDAO().queryForList("role.selectRoles", map);
	}

	public Object insertRole(Role role) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().insert("role.insertRole", role);
			Integer id = (Integer) this.getBaseDAO().queryForObject("role.selectLastInsertId");//获取刚才插入的数据的ID
			role.setId(id.toString());
			insertRoleAndResources(role);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return null;
	}

	public Object updateRole(Role role) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().update("role.updateRole", role);
			this.getBaseDAO().delete("role.deleteRoleAndResource", role);
			insertRoleAndResources(role);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return null;
	}
	/**
	 * 根据role的resourceIds属性批量插入RoleAndResource
	 * @throws SQLException 
	 * */
	private void insertRoleAndResources(Role role) throws SQLException{
		String resourceIds = role.getResourceIds();
		if(resourceIds!=null&&!"".equals(resourceIds)){
			String[] resourceIdArray = resourceIds.split(",");
			for (String rId : resourceIdArray) {
				RoleAndResource rar = new RoleAndResource();
				rar.setRole_id(role.getId());
				rar.setResource_id(rId);
				this.getBaseDAO().insert("role.insertRoleAndResource",rar);
			}
		}
	}

	public int deleteRole(Role role) throws SQLException {
		try {
			this.getBaseDAO().startTransaction();
			this.getBaseDAO().delete("role.deleteRole", role);
			this.getBaseDAO().delete("role.deleteRoleAndResource", role);
			this.getBaseDAO().delete("role.deleteUsergroupAndRole", role);
//			insertRoleAndResources(role);
			this.getBaseDAO().commitTransaction();
		} finally {
			this.getBaseDAO().endTransaction();
		}
		return 0;
	}
}
